package com.wlhse.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wlhse.dao.AppServiceDao;
import com.wlhse.entity.AppServicePojo;
import com.wlhse.exception.WLHSException;
import com.wlhse.service.AppService;
import com.wlhse.util.SqliteUtil;
import com.wlhse.util.state_code.CodeDict;
import com.wlhse.util.state_code.NR;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class AppServiceImpl implements AppService {
    @Resource
    private SqliteUtil sqliteUtil;

    @Resource
    private AppServiceDao appServiceDao;

    @Resource
    private AppServicePojo appServicePojo;


    private void setFile(MultipartFile file, String str) throws Exception {
        String rootPath = System.getProperty("catalina.home") + "\\webapps\\" + str;
        // 原始名称
        String fileName = file.getOriginalFilename();
        File newFile = new File(rootPath + File.separator + File.separator + fileName);
        if (!newFile.getParentFile().exists()) {
            newFile.getParentFile().mkdirs();
        }
        file.transferTo(newFile);
    }

    @Override
    @Transactional
    public String updateSql(String version) {
        if (!StringUtils.isNotBlank(version))
            throw new WLHSException("更新失败");
        String rootPath = System.getProperty("catalina.home") + "\\webapps\\";
        String fileName = "sqltransform";
        File newFile = new File(rootPath + File.separator + fileName);
        if (!newFile.exists()) {
            newFile.mkdirs();
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String sqlFileName = df.format(new Date());//系统时间
        String sqlitePath = null;//sqlite
        try {
            sqlitePath = sqliteUtil.gather(newFile.getPath(), sqlFileName);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        String sqliteAllPath = newFile.getPath() + File.separator + "sqlite" + sqlitePath;
        File sqliteFile = new File(sqliteAllPath);
        String[] a = version.split("\\.");
        appServicePojo.setServerVersion1(a[0]);
        appServicePojo.setServerVersion2(a[1]);
        appServicePojo.setServerVersion3(a[2]);
        appServicePojo.setSqlAddress("sqltransform/" + "sqlite" + sqlitePath);
        if (!sqliteFile.exists())
            throw new WLHSException("更新失败");
        //调用dao层接口，往数据库中更新版本号
        appServiceDao.addDataConfig(appServicePojo);
        appServiceDao.updateDataConfig();
        return NR.r();
    }

    @Override
    @Transactional
    public String updateApk(MultipartFile file) {
        if (!StringUtils.isNotBlank(file.getOriginalFilename()))
            throw new WLHSException("上传失败");
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String apkDateName = df.format(new Date());
        String apkFileName = "updateApk" + File.separator + apkDateName;
        try {
            setFile(file, apkFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject object = new JSONObject(true);
        object.put("code", CodeDict.SUCCESS);
        object.put("message", "操作成功");
        object.put("fileName", "updateApk" + "/" + apkDateName + "/" + file.getOriginalFilename());
        return object.toJSONString();
    }

    @Override
    @Transactional
    public String updateTime(AppServicePojo appServicePojo) {
        String version = appServicePojo.getVersion();
        String[] a = version.split("\\.");
        appServicePojo.setServerVersion1(a[0]);
        appServicePojo.setServerVersion2(a[1]);
        appServicePojo.setServerVersion3(a[2]);
        if (appServiceDao.addApkUploadToSql(appServicePojo) <= 0)
            throw new WLHSException("更新失败");
        appServiceDao.updateDataConfig();
        return NR.r();
    }

    @Override
    public String getVersion(int value, String isOrderBy) {
        List<AppServicePojo> list = appServiceDao.queryVersionByEnabled(value, isOrderBy);
        if (appServiceDao.queryVersionByEnabled(value, isOrderBy).size() != 0) {
            return NR.r(list, 0, 0);
        } else if (appServiceDao.queryVersionByEnabled(value, isOrderBy).size() == 0 && value == 1) {
            appServicePojo.setServerVersion1("0");
            appServicePojo.setServerVersion2("0");
            appServicePojo.setServerVersion3("0");
            list.add(appServicePojo);
            return NR.r(list, 0, 0);
        } else if (appServiceDao.queryVersionByEnabled(value, isOrderBy).size() == 0 && value == 0) {
            return NR.r(null, 0, 0);
        } else {
            throw new WLHSException("查询失败");
        }
    }

    @Override
    @Transactional
    public String updateEnable(int id) {
        if (appServiceDao.updateVersion(id) <= 0)
            throw new WLHSException("更新失败");
        return NR.r();
    }
}
